package com.skyline.user.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.skyline.base.dao.impl.BaseDaoImpl;
import com.skyline.base.type.Activity;
import com.skyline.user.dao.BasicUserDao;
import com.skyline.user.mapper.UserMapper;
import com.skyline.user.model.User;

//TODO:加注释
@Repository("basicUserDao")
public class BasicUserDaoImpl extends BaseDaoImpl implements BasicUserDao {
	/**
	 * insert into user
	 * (email,password,nickname,portrait,createdate,updatetime,lastloginIP
	 * ,lastlogintime,authority,activity) values (?,?,?,"default",?,?,?,?,0,?)
	 * */
	@Value("${BasicUserDao.insertUser}")
	private String insertUserSql;

	/**
	 * select * from user where id=? and activity!=?
	 * */
	@Value("${BasicUserDao.queryUserById}")
	private String queryUserByIdSql;

	/**
	 * select * from user where email=? and activity!=?
	 * */
	@Value("${BasicUserDao.queryUserByEmail}")
	private String queryUserByEmailSql;

	/**
	 * update user set lastloginIP=? , lastlogintime=? where email=?
	 * */
	@Value("${BasicUserDao.updateLoginInfo}")
	private String updateLoginInfoSql;

	/**
	 * select * from user where email=? and password=? and activity!=?
	 * */
	@Value("${BasicUserDao.queryUserByEmailAndPassword}")
	private String queryUserByEmailAndPasswordSql;

	@Override
	public void insertUser(String email, String password, String ip) {
		// Date createtime = new Date();
		jdbcTemplate.update(insertUserSql, new Object[] { email, password, email, ip, Activity.NORMAL.toString() });
	}

	@Override
	public User queryUserById(Long userid) {
		List<User> users = jdbcTemplate.query(queryUserByIdSql, UserMapper.getMapper(), userid, Activity.NORMAL.toString());
		if (users.size() == 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public User queryUserByEmail(String email) {
		List<User> users = jdbcTemplate.query(queryUserByEmailSql, UserMapper.getMapper(), email, Activity.NORMAL.toString());
		if (users.size() == 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public User queryUserByEmailAndPassword(String email, String password) {
		List<User> users = jdbcTemplate.query(queryUserByEmailAndPasswordSql, UserMapper.getMapper(), email, password,
				Activity.NORMAL.toString());
		if (users.size() == 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public int countUserByEmail(String email) {
		return getCountResult(queryUserByEmailSql, email, Activity.NORMAL.toString());
	}

	@Override
	public void updateLoginInfo(final long id, final String loginIP) {
		jdbcTemplate.update(updateLoginInfoSql, loginIP, id);
	}

}
